package com.zb.servlet;

import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ConcurrentAccessException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.zb.bean.User;
import com.zb.service.UserService;
import com.zb.util.CryptoUtils;
import com.zb.util.LoggerUtil;
import com.zb.util.web.HttpMethod;
import com.zb.util.web.HttpUtils;

public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public LoginServlet() {
        super();
    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse response)
            throws ServletException, IOException {
        String loginType = req.getParameter("loginType");
        String userName = req.getParameter("userName");
        String password = req.getParameter("password");
        String rememberMe = req.getParameter("rememberMe");

        // 错误消息
        String loginErrorMsg = "";
        UsernamePasswordToken token = new UsernamePasswordToken(userName,
                CryptoUtils.encodeMD5(password));
        Subject subject = null;
        try {
            // 设置是否记住我
            if (null == rememberMe || "".equals(rememberMe.trim()) || "off".equals(rememberMe)) {
                token.setRememberMe(false);
            } else {
                token.setRememberMe(true);
            }
            SecurityUtils.getSubject().login(token);
            subject = SecurityUtils.getSubject();
            LoggerUtil.LoggerFormatPattern("用户：{0} 登录成功", subject.getPrincipal());

            SecurityUtils.getSubject().getSession().setTimeout(1000 * 60 * 60);
            req.getSession().setAttribute("nickName", subject.getPrincipal());
        } catch (Throwable e) {
            // UnknownAccountException 该账号不存在
            // CredentialsException 密码错误
            if (e instanceof LockedAccountException) {
                loginErrorMsg = "该账号已被锁定，请联系管理员解锁";
            } else if (e instanceof ConcurrentAccessException) {
                loginErrorMsg = "该账户已经登录";
            } else if (e instanceof AuthenticationException) {
                loginErrorMsg = "账号不存在或密码错误";
            } else {
                LoggerUtil.LoggerWarn("未知的登陆错误", e);
                loginErrorMsg = "未知的登陆错误";
            }
        }

        // 登录出现错误
        if (!"".equals(loginErrorMsg) && loginErrorMsg.length() > 0) {
            req.setAttribute("loginErrorMsg", loginErrorMsg);
            if (loginType != null && loginType.equals("mobile")) {// 手机端登录
                req.getRequestDispatcher("/mobile/login").forward(req, response);
            }else{
                req.getRequestDispatcher("/toLogin").forward(req, response);
            }
        }
        if ("".equals(loginErrorMsg) || loginErrorMsg.length() == 0 ) {
            /**
             * 利用ModelAndView也能实现forward、redirect： forward转发: return
             * ModelAndView("forward:/index/mailList.shtml"); redirect重定向: return
             * ModelAndView("redirect:/index/mailList.shtml");
             */
            /*
             * if(subject.getPrincipal().equals("zhoubang")){ return
             * this.redirectModelAndView("/system"); }else{ if(loginType != null &&
             * loginType.equals("mobile")){//手机端登录，跳转到手机端首页 return
             * this.redirectModelAndView("/mobile/index"); } return
             * this.redirectModelAndView("/center"); }
             */
            ServletContext servletContext = this.getServletContext();  
            WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);  
            UserService userService = (UserService) context.getBean("userServiceImpl"); 
            
            User userInfo = null;
            try {
                userInfo = userService.getUserByName(userName);
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            String url = "http://api.uyan.cc?mode=des&uid=" + userInfo.getId()
                    + "&uname=" + URLEncoder.encode(userInfo.getUserName(),"UTF-8")
                    + "&email=" + URLEncoder.encode(userInfo.getEmail() == null ? "" : userInfo.getEmail(),"UTF-8")
                    + "&uface=&ulink=&expire=3600&key="
                    + URLEncoder.encode("gnabuohz58","UTF-8");

            String desstr = null;
            try {
                desstr = HttpUtils.getString(url, HttpMethod.GET);
            } catch (Exception e) {
                e.printStackTrace();
            }

            Cookie cookie = new Cookie("syncuyan", desstr);
            cookie.setPath("/");
            cookie.setMaxAge(3600);
            cookie.setDomain("www.2b2b92b.com");
            response.addCookie(cookie);
            //response.sendRedirect("/index/index");
            req.getRequestDispatcher("/index/index").forward(req, response);
        }
    }

}
